import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_aygsh/base/Constant.dart';
import 'package:flutter_aygsh/http/Api.dart';
import 'package:flutter_aygsh/http/HttpUtil.dart';
import 'package:flutter_aygsh/util/PreviewImagesWidget.dart';
import 'package:flutter_aygsh/util/SignUtil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'CommentEntity.dart';

class GoodsCommentListPage extends StatefulWidget {
  String course_id;
  GoodsCommentListPage({Key key, @required this.course_id}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAddressView();
  }
}

class MyAddressView extends State<GoodsCommentListPage> {
  List<GoodsCommentDataData> timeList = new List();
  int page = 1;
  String token = "";
  String name = "";
  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadList();
  }

  loadList() async {
    Map map = new Map();
    map['goods_id'] = widget.course_id;
    map['p'] = page.toString();
    map['per'] = "10";
    map['sign_type'] = createSignType(Api.URL_GOODS_COMMENTLIST);
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODS_COMMENTLIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (mounted) if (page == 1) {
      _controller.finishRefresh();
    } else {
      _controller.finishLoad();
    }
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    GoodsCommentEntity homeListEntity =
        new GoodsCommentEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          timeList.clear();
          timeList.addAll(homeListEntity.data.datas);
        } else {
          timeList.addAll(homeListEntity.data.datas);
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text('全部评论',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(35),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: new Container(
          color: f0Color,
          child: Column(
            children: <Widget>[
              // Container(
              //   padding: EdgeInsets.all(10),
              //   color: f0Color,
              //   child: Row(
              //     children: <Widget>[
              //       Expanded(
              //         flex: 1,
              //         child: Container(
              //           margin: EdgeInsets.fromLTRB(
              //               ScreenUtil.getInstance().setHeight(DP_10),
              //               0,
              //               ScreenUtil.getInstance().setHeight(DP_10),
              //               0),
              //           height: ScreenUtil.getInstance().setHeight(DP_60),
              //           decoration: BoxDecoration(
              //               color: white,
              //               borderRadius: BorderRadius.circular(20.0)),
              //           child: ConstrainedBox(
              //             constraints: BoxConstraints(maxHeight: DP_80),
              //             child: TextField(
              //               keyboardAppearance: Brightness.light,
              //               maxLines: 1,
              //               onChanged: (value) {
              //                 name = value;
              //               },
              //               cursorColor: mainColor,
              //               decoration: new InputDecoration(
              //                   // contentPadding: EdgeInsets.all(0),
              //                   prefixIcon: Icon(
              //                     Icons.search,
              //                     color: Colors.black45,
              //                   ),
              //                   hintText: "姓名、手机号",
              //                   border: InputBorder.none,
              //                   hintStyle: TextStyle(
              //                       color: Colors.black45,
              //                       fontSize: ScreenUtil.getInstance()
              //                           .setSp(NORMAL_FONT_SIZE))),
              //             ),
              //           ),
              //         ),
              //       ),
              //       GestureDetector(
              //         behavior: HitTestBehavior.opaque,
              //         child: Container(
              //             alignment: Alignment.center,
              //             width: ScreenUtil.getInstance().setWidth(DP_80),
              //             child: Text('搜索',
              //                 style: TextStyle(
              //                     color: black_99,
              //                     fontSize: ScreenUtil.getInstance()
              //                         .setSp(NORMAL_FONT_SIZE)))),
              //         onTap: () {
              //           page = 1;
              //           loadList();
              //         },
              //       )
              //     ],
              //   ),
              // ),
              Expanded(
                child: new EasyRefresh(
                  enableControlFinishRefresh: true,
                  enableControlFinishLoad: true,
                  header: MaterialHeader(),
                  footer: MaterialFooter(),
                  controller: _controller,
                  child: ListView.separated(
                      itemBuilder: _renderRow,
                      separatorBuilder: (BuildContext context, int index) {
                        return Container(
                          color: divideColor,
                          height: 1,
                        );
                      },
                      itemCount: timeList.length),
                  onRefresh: () async {
                    page = 1;
                    loadList();
                  },
                  onLoad: () async {
                    page++;
                    loadList();
                  },
                ),
              ),
            ],
          )),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new Container(
      color: white,
      padding: EdgeInsets.only(left: 15, right: 15, bottom: 5, top: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              ClipOval(
                  child: timeList[index].user_avatar == "null"
                      ? Image.asset('images/logo.png',
                          fit: BoxFit.fill,
                          width: ScreenUtil.getInstance().setHeight(DP_50 + 5),
                          height: ScreenUtil.getInstance().setHeight(DP_50 + 5))
                      : CachedNetworkImage(
                          imageUrl: timeList[index].user_avatar.contains("http")
                              ? timeList[index].user_avatar
                              : Api.ImgBaseUrl + timeList[index].user_avatar,
                          width: ScreenUtil.getInstance().setHeight(DP_50 + 5),
                          fit: BoxFit.fill,
                          height:
                              ScreenUtil.getInstance().setHeight(DP_50 + 5))),
              Container(width: 10),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(timeList[index].user_nickname,
                      style: TextStyle(
                          color: Colors.black87,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE - 3))),
                  Text(timeList[index].comment_time,
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(SMALL_FONT_SIZE - 3))),
                ],
              )
            ],
          ),
          Container(height: 10),
          Text(timeList[index].content,
              style: TextStyle(
                  color: Colors.black87,
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
          Container(height: 5),
          timeList[index].imgList.length == 0
              ? Container()
              : Container(
                  // height: 10 +
                  //     (MediaQuery.of(context).size.width -
                  //             ScreenUtil.getInstance().setHeight(DP_80)) /
                  //         3,
                  child: GridView.builder(
                    itemCount: timeList[index].imgList.length,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        mainAxisSpacing:
                            ScreenUtil.getInstance().setHeight(DP_20),
                        crossAxisSpacing: 10.0,
                        crossAxisCount: 3),
                    itemBuilder: (BuildContext context, int i) {
                      return GestureDetector(
                        onTap: () {
                          List<String> imgs = new List();
                          for (int i = 0;
                              i < timeList[index].imgList.length;
                              i++) {
                            String m2 = timeList[index]
                                .imgList[i]
                                .replaceAll('{img:', '');
                            String m3 = m2.replaceAll('}', '');
                            imgs.add(Api.ImgBaseUrl + m3);
                          }
                          Navigator.of(context).push(PageRouteBuilder(
                              pageBuilder: (c, a, s) => PreviewImagesWidget(
                                    imgs,
                                    initialPage: i,
                                  )));
                        },
                        child: CachedNetworkImage(
                            imageUrl:
                                Api.ImgBaseUrl + timeList[index].imgList[i],
                            height: (MediaQuery.of(context).size.width -
                                    ScreenUtil.getInstance().setHeight(DP_80)) /
                                3,
                            fit: BoxFit.cover,
                            width: (MediaQuery.of(context).size.width -
                                    ScreenUtil.getInstance().setHeight(DP_80)) /
                                3),
                      );
                    },
                  ),
                ),
          // Text(timeList[index].sku,
          //     style: TextStyle(
          //         color: Colors.black54,
          //         fontSize:
          //             ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE - 1))),
          // Container(height: 10),
        ],
      ),
    );
  }
}
